﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Reflection;
using Metaspec;

namespace CodeSnippetExample
{
	class Program
	{
		static void Main(string[] args)
		{
			snippet_example();
			context_snippet_example();
		}

		//Can be used for parsing snippets
		static void snippet_example()
		{
			string text = @"
			for ( int i = 0; i != 10; ++i )
			{

			}
			";

			ICsProject project = ICsProjectFactory.create(project_namespace.pn_project_namespace);
			ICsSnippet snippet = ICsSnippetFactory.create(text.ToCharArray(), null);

			project.parseSnippet(snippet, CsExpectedSnippet.cses_all, null, true);

			CsNode node = snippet.getNodes()[0];
			Debug.Assert(node.e == cs_node.n_for_statement);
		}

		//Can be used for break point conditional expression evaluation, etc
		static void context_snippet_example()
		{
			string text = @"
class Program
{
	void sum(int a,int b)
	{
		return a + b;
	}
}
";

			string snippet_text = @"
a * b
";

			//project
			ICsProject project = ICsProjectFactory.create(project_namespace.pn_project_namespace);

			//assembly
			string assembly_path = Assembly.GetAssembly(typeof(object)).Location;
			byte[] assembly_buffer = File.ReadAllBytes(assembly_path);
			IExternalAssemblyModule module = IExternalAssemblyModuleFactory.create(assembly_buffer, assembly_path);
			project.addExternalAssemblyModules(new IExternalAssemblyModule[] { module }, false, null);

			//add files
			char[] chars = new char[text.Length + 1];
			text.ToCharArray().CopyTo(chars, 0);
			//last char in file must be '\0'
			chars[text.Length] = '\0';
			ICsFile file = ICsFileFactory.create(chars, "text.cs");
			project.addFiles(file);

			//set generate entity model flag
			project.setBuildEntityModel(true);

			//parse project
			project.parse(true, true);

			CsNode context_node = ((CsMethod)((CsClass)file.getCompilationUnit().declarations[0]).member_declarations[0]).definition.statements[0];
			CsFormalParameter parameter1_node = ((CsMethod)((CsClass)file.getCompilationUnit().declarations[0]).member_declarations[0]).parameters.parameters.First.Value;
			CsFormalParameter parameter2_node = ((CsMethod)((CsClass)file.getCompilationUnit().declarations[0]).member_declarations[0]).parameters.parameters.First.Next.Value;

			//parse context snippet
			ICsSnippet snippet = ICsSnippetFactory.create(snippet_text.ToCharArray(), null);
			project.parseSnippet(snippet, CsExpectedSnippet.cses_all, context_node, true);

			CsBinaryExpression snippet_node = (CsBinaryExpression)snippet.getNodes()[0];
			Debug.Assert(snippet_node.lhs.entity == parameter1_node.entity);
			Debug.Assert(snippet_node.rhs.entity == parameter2_node.entity);
		}
	}
}
